import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

import java.util.concurrent.atomic.AtomicInteger;

public class RequestMessageResolver extends Resolver {

    private static final AtomicInteger counter = new AtomicInteger(1);

    @Override
    boolean support(IMessage iMessage) {
        return MessageTypeEnum.REQUEST.equals(iMessage.getType());
    }

    @Override
    IMessage resolver(IMessage iMessage, ChannelHandlerContext ctx) {
        int index = counter.getAndIncrement();
        Channel channel = ServerMessageHandler.channelMap.get(iMessage.getTo());
        System.out.println("[" + iMessage.getFrom() + "] 发送给 [" + iMessage.getTo() + "(" + (channel == null ? "未登录" : "已登录") + ")" + "] " + index + " . receive request:" + iMessage.getBody());
        if (channel != null) {
            channel.writeAndFlush(iMessage);
        }
        IMessage response = new IMessage();
        response.setType(MessageTypeEnum.RESPONSE);
        response.setFrom("服务器");
        AttributeKey<String> attributeKey = AttributeKey.valueOf("username");
        response.setTo(ctx.channel().attr(attributeKey).get());
        response.setBody(channel == null ? "对方未登录" : "发送成功!");
        return response;
    }


}
